//
//  Validate(extension).swift
//  SwiftCommon
//
//  Created by 董振山 on 2018/7/2.
//  Copyright © 2018年 董振山. All rights reserved.
//

import Foundation

enum ValidateType {
    /// 手机号
    case mobile
    /// 身份证号
    case IDNumber
    /// 是否存数字
    case Number
    /// 字符长度 传入长度
    case ChatNumber(Int)
    /// 邮箱
    case email
    /// 自定义 传入格式
    case custom(String)
}

extension String{
    /** 正则判断
     * @param type 正则验证类型
     */
    func validate(_ type:ValidateType) -> Bool{
        var mobileReg = ""
        switch type {
        case .mobile:
            mobileReg = "^1[3456789]\\d{9}$"
            break
        case .IDNumber:
            mobileReg = "^(\\d{14}|\\d{17})(\\d|[xX])$"
            break
        case .Number:
            mobileReg = "^[0-9]*$"
            break
        case .ChatNumber(let length):
            mobileReg = "^\\d{\(length)}$"
            break
        case .email:
            mobileReg = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
            break
        case .custom(let format):
            mobileReg = format
            break
        }
        let predicate = NSPredicate(format:"SELF MATCHES %@",mobileReg )
        if predicate.evaluate(with: self) {
            return true
        }else{
            return false
        }
    }

}
